package com.hxd.otc.base;

import android.arch.lifecycle.Lifecycle;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.baidu.mobstat.StatService;
import com.hxd.otc.dialog.LoadingDialog;
import com.hxd.otc.mvp.base.BasePresenter;
import com.hxd.otc.mvp.base.IBaseView;
import com.hxd.otc.widget.BlocksToast;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.AutoDisposeConverter;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 作  者 :  胡庆岭
 * 时  间 :  2018/6/1 10:46
 * 描  述 :  ${TODO} Fragment Base类
 */
public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements IBaseView {

    protected Unbinder mUnbinder;

    protected View mRootView;

    @NonNull
    protected Context mContext;

    protected P mPresenter;

    protected LoadingDialog spinnerDlg;//等待框

    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void initEvent();

    protected abstract P createPresenter();

    public BaseFragment() {
        mPresenter = createPresenter();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(getLayoutId(), container, false);
            mUnbinder = ButterKnife.bind(this, mRootView);
        }

        initView();

        initData();

        initEvent();

        return mRootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public <X> AutoDisposeConverter<X> bindAutoDispose() {
        return AutoDispose.autoDisposable(AndroidLifecycleScopeProvider
                .from(this, Lifecycle.Event.ON_DESTROY));
    }

    /**
     * /订阅的事件立即被消费
     *
     * @param event
     */
    protected void post(Object event) {
        EventBus.getDefault().post(event);
    }

    /**
     * 当你希望你的事件不被马上处理的时候，举个栗子，比如说，在一个详情页点赞之后，产生一个VoteEvent，
     * VoteEvent并不立即被消费，而是等用户退出详情页回到商品列表之后，接收到该事件，
     * 然后刷新Adapter等。其实这就是之前我们用startActivityForResult和onActivityResult做的事情。
     *
     * @param event
     */
    protected void postSticky(Object event) {
        EventBus.getDefault().postSticky(event);
    }

    /**
     * 注册 EventBas EventBus  3.0 注册方式只有一个
     */
    public void registerEventBus() {
        EventBus.getDefault().register(this);
    }

    /**
     * 解除绑定
     */
    protected void unregisterEventBus() {
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
        if (mPresenter != null) mPresenter.destroy();//释放资源
        this.mPresenter = null;

        if (EventBus.getDefault().isRegistered(this)) {
            unregisterEventBus();
        }
        dismissSpinnerDlg();
    }

    protected void $startActivity(@NonNull Class clazz) {
        if (getActivity() != null) {
            startActivity(new Intent(getActivity(), clazz));
        }
    }

    protected void $startActivity(@NonNull Class clazz, boolean isFinish) {
        $startActivity(clazz);
        if (isFinish && getActivity() != null) {
            getActivity().finish();
        }
    }

    protected void $startActivity(@NonNull Class clazz, @NonNull Bundle bundle) {
        if (getActivity() == null) {
            return;
        }
        Intent intent = new Intent(getActivity(), clazz);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    protected void $startActivity(@NonNull Class clazz, @NonNull Bundle bundle, boolean isFinish) {
        $startActivity(clazz, bundle);
        if (isFinish && getActivity() != null) {
            getActivity().finish();
        }
    }

    protected Bundle getBundle() {
        FragmentActivity activity = getActivity();
        if (activity == null) {
            return null;
        }
        Intent intent = activity.getIntent();
        if (intent == null) {
            activity.finish();
            return null;
        }
        return intent.getExtras();
    }

    protected void $startActivityForResult(@NonNull Class clazz, int requestCode) {
        startActivityForResult(new Intent(getActivity(), clazz), requestCode);
    }

    protected void $startActivityForResult(@NonNull Class clazz, int requestCode, boolean isFinish) {
        $startActivityForResult(clazz, requestCode);
        if (isFinish && getActivity() != null) {
            getActivity().finish();
        }

    }

    protected void $startActivityForResult(@NonNull Class clazz, int requestCode, Bundle bundle, boolean isFinish) {
        Intent intent = new Intent(getActivity(), clazz);
        intent.putExtras(bundle);
        startActivityForResult(intent, requestCode);
        if (isFinish && getActivity() != null) {
            getActivity().finish();
        }
    }

    protected void $finish() {
        if (getActivity() != null) {
            getActivity().finish();
        }
    }

    @Override
    public void showToast(@NonNull String toast) {
        BlocksToast.get().showToast(toast);
    }

    @Override
    public void onShowLoading() {

    }

    @Override
    public void onHideLoading() {

    }

    @Override
    public void onError(int code) {

    }

    /**
     * 显示加载对话框
     *
     * @param msg
     * @param isCancel
     */
    protected void showSpinnerDlg(String msg, boolean isCancel) {
        if (spinnerDlg == null) {
            spinnerDlg = new LoadingDialog(mContext);
        }
        spinnerDlg.setText(msg).setCancel(isCancel).show();
    }

    /**
     * 关闭加载对话框
     */
    protected void dismissSpinnerDlg() {
        if (spinnerDlg != null && spinnerDlg.isShowing()) {
            spinnerDlg.dismiss();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        StatService.onPageStart(getActivity(), this.getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        StatService.onPageEnd(getActivity(), this.getClass().getSimpleName());
    }
}
